package com.botarena.server.servlets.http;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.botarena.server.model.Account;
import com.botarena.server.services.AccountService;
import com.google.appengine.api.datastore.Blob;

public class ImageServlet extends HttpServlet {

        private static final long serialVersionUID = 2947991631037962748L;

        private static final AccountService accountService = new AccountService();
        
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                
                String avatar = request.getParameter("avatar");
                
                try {
                        response.setContentType("image/jpeg");
                        
                        if (avatar != null) {
                                Account account = accountService.getByKey(avatar);
                                Blob data = account.getAvatar();
                                if (data != null) {
                                        response.getOutputStream().write(data.getBytes());
                                }
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                        String error = "Cannot create account: " + e.getMessage();
                        response.getOutputStream().write(error.getBytes());
                } finally {
                        response.getOutputStream().close();
                }
        }
}
